package avicit.bdp.dms.tdm.service;

import avicit.bdp.common.base.BaseService;
import avicit.bdp.common.database.ColumnMeta;
import avicit.bdp.common.utils.BdpLogUtil;
import avicit.bdp.common.utils.CheckParaUtils;
import avicit.bdp.common.utils.DateUtils;
import avicit.bdp.core.constant.Constants;
import avicit.bdp.core.util.json.JSONUtils;
import avicit.bdp.dms.dss.dto.ApiParamDto;
import avicit.bdp.dms.dss.service.DataResourceService;
import avicit.bdp.dms.tdm.dao.AssetApplyDao;
import avicit.bdp.dms.tdm.dao.AssetPortalDao;
import avicit.bdp.dms.tdm.dto.AssetApplyDTO;
import avicit.bdp.dms.tdm.dto.AssetLogDTO;
import avicit.bdp.dms.tdm.dto.AssetTagDTO;
import avicit.bdp.dms.tdm.dto.BdpAssetDTO;
import avicit.bdp.dms.tdm.dto.BdpAssetMountDataServiceDTO;
import avicit.bdp.dms.tdm.dto.BdpAssetMountFileDTO;
import avicit.bdp.dms.tdm.dto.BdpAssetMountReportDTO;
import avicit.bdp.dms.tdm.dto.ColumnDTO;
import avicit.bdp.dms.tdm.service.adapter.DataServiceAdapter;
import avicit.bdp.dms.tdm.service.adapter.FileAdapter;
import avicit.bdp.dms.tdm.service.adapter.ModelAdapter;
import avicit.bdp.dms.tdm.utils.ApplyServiceType;
import avicit.bdp.dms.tdm.utils.CheckerStatus;
import avicit.bdp.dms.tdm.utils.ResourceType;
import avicit.platform6.api.system.ConvertColumnClient;
import avicit.platform6.api.system.SysDeptClient;
import avicit.platform6.api.system.SysOrgClient;
import avicit.platform6.api.system.SysUserClient;
import avicit.platform6.api.system.impl.SystemConstant;
import avicit.platform6.api.sysuser.dto.SysDept;
import avicit.platform6.api.sysuser.dto.SysOrg;
import avicit.platform6.commons.utils.BusinessUtil;
import avicit.platform6.commons.utils.ComUtil;
import avicit.platform6.core.context.ThreadContextHelper;
import avicit.platform6.core.exception.BusinessException;
import avicit.platform6.core.rest.msg.QueryRespBean;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @金航数码科技有限责任公司
 * @作者：${tableInfo.classCreator}
 * @邮箱：${tableInfo.classMailbox}
 * @创建时间： 2023-11-14 16:04
 * @类说明：bdp_asset_portalService
 * @修改记录：
 */
@Service
public class AssetPortalService extends BaseService<AssetPortalDao, BdpAssetDTO> {

    private static final Logger logger = LoggerFactory.getLogger(AssetPortalService.class);

    @Autowired
    private AssetPortalDao asssetPortalDao;
    @Autowired
    private AssetApplyDao assetApplyDao;
    @Autowired
    private AssetLogService assetLogService;
    @Autowired
    private DataServiceAdapter dataServiceAdapter;
    @Autowired
    private ModelAdapter modelAdapter;
    @Autowired
    private FileAdapter fileAdapter;
    @Autowired
    private ConvertColumnClient convertColumnClient;
    @Autowired
    private SysOrgClient sysOrgClient;
    @Autowired
    private SysDeptClient sysDeptClient;
    @Autowired
    private DataResourceService dataResourceService;
    @Autowired
    private BdpAssetMountDataServiceService bdpAssetMountDataServiceService;
    @Autowired
    private BdpAssetMountReportService bdpAssetMountReportService;
    @Autowired
    private SysUserClient sysUserClient;
    @Autowired
    private AssetTagService assetTagService;
    @Autowired
    private BdpAssetService bdpAssetService;

    /**
     * 分页查询已发布资产
     *
     * @throws Exception
     */
    public QueryRespBean<BdpAssetDTO> getAssetPageList(String catalogId, String keyWords, String assetType,
                                                       String labels, String releaseDept, String sourceSystem, String viewSort, Integer pageNo,
                                                       Integer pageSize) throws Exception {
        QueryRespBean<BdpAssetDTO> queryRespBean = new QueryRespBean<>();

        if (StringUtils.isBlank(catalogId)) {
            return null;
        }

        List<String> labelList = new ArrayList<>();
        if (StringUtils.isNotBlank(labels)) {
            String[] arr = labels.trim().split(",");
            labelList = Arrays.asList(arr);
        }

        //当前用户组织id
        String releaseOrgId = ThreadContextHelper.getOrgId();

        //文档密级
        List<String> wordSecretList = ThreadContextHelper.getWordSecretList();
        PageHelper.startPage(pageNo, pageSize);

        //获取当前时间
        String currentDate = DateUtils.getSystemCurrentDate();
        Page<BdpAssetDTO> page = asssetPortalDao.getAssetPageList(catalogId, keyWords, assetType, labelList, releaseDept, sourceSystem, viewSort, wordSecretList, currentDate, releaseOrgId);
        valueConvertResource(page.getResult());
        queryRespBean.setResult(page);
        BdpLogUtil.log4Query(queryRespBean);
        return queryRespBean;
    }

    /**
     * 通过平台API将字段值转换为名称，包括通用选择组件、通用代码
     *
     * @param assetList
     */
    private void valueConvertResource(List<BdpAssetDTO> assetList) {
        //循环组装请求数据
        Map<String, Set<String>> convertFormData = new HashMap<>();
        for (BdpAssetDTO asset : assetList) {
            BusinessUtil.createConvertSet(convertFormData, Constants.BDP_DATA_SECRET_LEVEL_KEY, asset.getSecretLevel());
            BusinessUtil.createConvertSet(convertFormData, "BDP_DAM_RESOURCE_TYPE", asset.getAssetType());
            BusinessUtil.createConvertSet(convertFormData, "BDP_DAM_SHARE_TYPE", asset.getShareType());
            BusinessUtil.createConvertSet(convertFormData, "BDP_DAM_ASSET_SOURCE", asset.getSourceSystem());
            BusinessUtil.createConvertSet(convertFormData, SystemConstant.USER, asset.getReleaser());
            BusinessUtil.createConvertSet(convertFormData, SystemConstant.USER, asset.getCreatedBy());
            BusinessUtil.createConvertSet(convertFormData, SystemConstant.DEPT, asset.getReleaseDept());
        }
        if (convertFormData.size() > 0) {
            //获取请求结果
            Map<String, Map<String, String>> convertResultData = convertColumnClient.replace(convertFormData);
            Map<String, String> map = getAllSysOrgAndDept();
            List<String> assetIdList = assetList.stream().map(BdpAssetDTO::getId).collect(Collectors.toList());
            //List<BdpAssetMountFileDTO> assetMountList = asssetPortalDao.getAssetMountFileList(assetIdList);
            //Map<String, BdpAssetMountFileDTO> assetMountMap = assetMountList.stream().collect(Collectors.toMap(BdpAssetMountFileDTO::getAssetId, Function.identity()));
            String loginUserId = ThreadContextHelper.getUserId();
            //申请按钮
            List<AssetApplyDTO> assetApplyDTOList = assetApplyDao.getApplyListByIds(assetIdList, loginUserId);
            //已经申请的服务
            Map<String, String> assetApplyMap = handleAssetApply(assetApplyDTOList);
            //审核通过的申请服务
            Map<String, String> assetApplyCheckedMap = handleAssetApplyChecked(assetApplyDTOList);
            //标签
            List<AssetTagDTO> assetTagDTOList = assetTagService.findAssetTagListByAssetIdList(assetIdList);
            Map<String, String> assetTagdMap = handleAssetTag(assetTagDTOList);

            //循环设置Alias或Name的值
            for (BdpAssetDTO asset : assetList) {
                asset.setSecretLevelName(BusinessUtil.convertFormat(convertResultData, Constants.BDP_DATA_SECRET_LEVEL_KEY, asset.getSecretLevel()));
                //资源类型
                asset.setAssetTypeName(BusinessUtil.convertFormat(convertResultData, "BDP_DAM_RESOURCE_TYPE", asset.getAssetType()));
                //数据资产共享类型
                asset.setShareTypeName(BusinessUtil.convertFormat(convertResultData, "BDP_DAM_SHARE_TYPE", asset.getShareType()));
                //数据资产来源系统
                asset.setSourceSystemName(BusinessUtil.convertFormat(convertResultData, "BDP_DAM_ASSET_SOURCE", asset.getSourceSystem()));
                //发布人
                asset.setReleaserName(BusinessUtil.convertFormat(convertResultData, SystemConstant.USER, asset.getReleaser()));
                asset.setReleaseDeptName(BusinessUtil.convertFormat(convertResultData, SystemConstant.DEPT, asset.getReleaseDept()));
                //创建人
                asset.setCreatedName(BusinessUtil.convertFormat(convertResultData, SystemConstant.USER, asset.getCreatedBy()));
                asset.setReleaseScopeShowName(getOrgName(asset.getReleaseScope(), map));
                asset.setEffectiveTimeTypeStr(handelEffectiveTime(asset));
                //标签
                String tagNames = assetTagdMap.get(asset.getId());
                if (StringUtils.isNotBlank(tagNames)) {
                    asset.setLabelNames(tagNames);
                }
                //创建部门
//                SysUser createdBy = sysUserClient.getSysUserById(asset.getCreatedBy());
//                String deptName = createdBy.getDeptName();
                asset.setCreateDeptName(asset.getReleaseDeptName());


                handelButton(asset, assetApplyMap, assetApplyCheckedMap);
            }
        }
    }

    private Map<String, String> handleAssetTag(List<AssetTagDTO> assetTagDTOList) {
        Map<String, String> assetApplyMap = new HashMap<>();
        for (AssetTagDTO dto : assetTagDTOList) {

            if (assetApplyMap.containsKey(dto.getAssetId())) {
                String apply = assetApplyMap.get(dto.getAssetId());
                apply = apply + "," + dto.getTagName();
                assetApplyMap.put(dto.getAssetId(), apply);
            } else {
                assetApplyMap.put(dto.getAssetId(), dto.getTagName());
            }
        }
        return assetApplyMap;
    }

    /**
     * 审核通过的服务类型
     *
     * @param assetApplyDTOList
     * @return java.util.Map<java.lang.String, java.lang.String>
     */
    private Map<String, String> handleAssetApplyChecked(List<AssetApplyDTO> assetApplyDTOList) {
        Map<String, String> assetApplyMap = new HashMap<>();
        for (AssetApplyDTO dto : assetApplyDTOList) {
            //审核通过状态是3
            if (CheckerStatus.APPROVED.getCode() != dto.getCheckerStatus()) {
                continue;
            }
            if (assetApplyMap.containsKey(dto.getAssetId())) {
                String apply = assetApplyMap.get(dto.getAssetId());
                apply = apply + "," + dto.getApplyServiceType();
                assetApplyMap.put(dto.getAssetId(), apply);
            } else {
                assetApplyMap.put(dto.getAssetId(), dto.getApplyServiceType());
            }
        }
        return assetApplyMap;
    }

    /**
     * 已经申请的服务类型
     *
     * @param assetApplyDTOList
     * @return java.util.Map<java.lang.String, java.lang.String>
     */
    private Map<String, String> handleAssetApply(List<AssetApplyDTO> assetApplyDTOList) {
        Map<String, String> assetApplyMap = new HashMap<>();
        for (AssetApplyDTO dto : assetApplyDTOList) {
            //审核状态，1-待审批，3-审批通过，5-审批不通过，4-已撤回
            //
            if (CheckerStatus.NOT_APPROVED.getCode() == dto.getCheckerStatus()
                    || CheckerStatus.REVOKE_APPROVED.getCode() == dto.getCheckerStatus()) {
                continue;
            }
            if (assetApplyMap.containsKey(dto.getAssetId())) {
                String apply = assetApplyMap.get(dto.getAssetId());
                apply = apply + "," + dto.getApplyServiceType();
                assetApplyMap.put(dto.getAssetId(), apply);
            } else {
                assetApplyMap.put(dto.getAssetId(), dto.getApplyServiceType());
            }
        }
        return assetApplyMap;
    }

    /**
     * 处理各种按钮状态
     *
     * @param asset
     * @return
     */
    private void handelButton(BdpAssetDTO asset, Map<String, String> assetApplyMap, Map<String, String> assetApplyCheckedMap) {
        // 资产公开或是不带身份的资产门户界面进来，则显示资产发布的服务
        if ("1".equals(asset.getShareType()) || StringUtils.isBlank(ThreadContextHelper.getUserId())) {
            // 公开,无需申请可直接访问
            handelOpenServiceTypeButton(asset, asset.getOpenServiceType());
        } else {
            String apply = assetApplyMap.get(asset.getId());
            if (apply == null || serviceTypeCompare(asset.getOpenServiceType(), apply)) {
                asset.setApplyButton("1");
            }
            // 根据申请的服务类型显示按钮
            String applyChecked = assetApplyCheckedMap.get(asset.getId());
            handelOpenServiceTypeButton(asset, applyChecked);

        }
    }

    /**
     * 各种按钮 0：显示，1：隐藏
     *
     * @param asset
     */
    private void handelOpenServiceTypeButton(BdpAssetDTO asset, String openServiceType) {
        // 开放服务类型[1-数据查询/2-数据推送/3-API接口/4-下载/5-模型/6-报表]
        if (StringUtils.isNotEmpty(openServiceType)) {
            if (openServiceType.contains("1")) {
                asset.setQueryButton("1");
            }
            if (openServiceType.contains("2")) {
                asset.setPushButton("1");
            }
            if (openServiceType.contains("3")) {
                asset.setApiButton("1");
            }
            if (openServiceType.contains("4")) {
                asset.setDownloadButton("1");
            }
            if (openServiceType.contains("5")) {
                asset.setModelButton("1");
            }
            if (openServiceType.contains("6")) {
                asset.setReportButton("1");
            }
        }
    }

    private Map<String, String> getAllSysOrgAndDept() {
        Map<String, String> map = new HashMap<>();
        List<SysOrg> orgList = sysOrgClient.getAllSysOrgList();
        if (CollectionUtils.isNotEmpty(orgList)) {
            for (SysOrg org : orgList) {
                map.put(org.getId(), org.getOrgName());
            }
        }
        List<SysDept> deptList = sysDeptClient.getAllSysDeptList();
        if (CollectionUtils.isNotEmpty(deptList)) {
            for (SysDept dept : deptList) {
                map.put(dept.getId(), dept.getDeptName());
            }
        }
        return map;
    }

    private String getOrgName(String releaseScope, Map<String, String> map) {
        JSONArray array = JSONUtils.parseArray(releaseScope);
        List<String> idList = array.toJavaList(String.class);
        List<String> scopeNames = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(idList)) {
            for (String orgId : idList) {
                if (map.get(orgId) != null) {
                    scopeNames.add(map.get(orgId));
                }
            }
        }

        String releaseScopeShowName = "";
        if (CollectionUtils.isNotEmpty(scopeNames)) {
            releaseScopeShowName = String.join(",", scopeNames);
        }
        return releaseScopeShowName;
    }

    private String handelEffectiveTime(BdpAssetDTO asset) {
        String effectiveTimeTypeStr = "";
        if (asset.getEffectiveTimeType() == 1) {
            effectiveTimeTypeStr = asset.getEffectiveTimeStart() + "至" +
                    asset.getEffectiveTimeEnd();
        } else {
            effectiveTimeTypeStr = "长期有效";
        }
        return effectiveTimeTypeStr;
    }

    /**
     * 查询资产信息
     *
     * @param id
     * @return
     */
    public BdpAssetDTO getAssetById(String id) {
        BdpAssetDTO asset = this.selectByPrimaryKey(id);
        List<String> assetIdList = new ArrayList<>();
        assetIdList.add(asset.getId());
        List<BdpAssetMountFileDTO> assetMountList = asssetPortalDao.getAssetMountFileList(assetIdList);
        List<AssetApplyDTO> assetApplyDTOList = assetApplyDao.getApplyListByIds(assetIdList, ThreadContextHelper.getUserId());
        Map<String, String> applyMap = handleAssetApply(assetApplyDTOList);
        String applyType = MapUtils.getString(applyMap, asset.getId());
        if (CollectionUtils.isNotEmpty(assetMountList)) {
            String openServiceType = assetMountList.get(0).getOpenServiceType();
            if (StringUtils.isNotBlank(applyType)) {
                String types[] = applyType.split(",");
                for (String type : types) {
                    openServiceType = openServiceType.replaceAll(type, "");
                }
            }
            handelOpenServiceTypeButton(asset, openServiceType);
        }
        BdpLogUtil.log4Query(asset);
        return asset;
    }

    /**
     * 数据下载
     */
    public void download(String assetId, HttpServletResponse response) throws Exception {
        BdpAssetDTO asset = this.selectByPrimaryKey(assetId);
        CheckParaUtils.checkDbObjectValidity(asset, logger, String.format("没有查到数据，请确保id:%s的资产是否存在", assetId));
        String assetType = asset.getAssetType();
        AssetLogDTO logDTO = createAssetLog(assetId, ApplyServiceType.DOWNLOAD.getCode());
        try {
            if (assetType.equals(String.valueOf(ResourceType.DATA_SERVICE.getCode()))) {
                int size = dataServiceAdapter.downloadDataFromDBToCsv(assetId, response);
                logDTO.setCallResult("下载数据" + size + "条");
            } else if (assetType.equals(String.valueOf(ResourceType.MODEL.getCode()))) {
                modelAdapter.downloadModel(assetId, response);
                logDTO.setCallResult("下载模型成功");
            }

            logDTO.setCallStatus(1);
            //增加调用次数
            bdpAssetService.addCallCount(assetId);
        } catch (Exception e) {
            logDTO.setCallStatus(0);
            logDTO.setCallResult(e.getMessage());
            logger.error("下载数据异常", e);
            throw e;
        }

        logDTO.setEndTime(new Date());
        assetLogService.insert(logDTO);
    }

    /**
     * 数据查询
     *
     * @param assetId
     * @throws Exception
     */
    public Map<String, Object> queryTableData(String assetId, Integer pageNo, Integer pageSize) throws Exception {
        BdpAssetDTO asset = this.selectByPrimaryKey(assetId);
        CheckParaUtils.checkDbObjectValidity(asset, logger, String.format("没有查到数据，请确保id:%s的资产是否存在", assetId));

        Map<String, Object> map = new HashMap<>(8);
        AssetLogDTO logDTO = createAssetLog(assetId, ApplyServiceType.DATA_QUERY.getCode());
        try {
            map = dataServiceAdapter.getDataListFromDB(assetId, pageNo, pageSize, null);
            logDTO.setCallStatus(1);
            logDTO.setCallResult("查询数据成功");
        } catch (Exception e) {
            logDTO.setCallStatus(0);
            logDTO.setCallResult(e.getMessage());
            logger.error("查询数据异常", e);
            throw e;
        }

        logDTO.setEndTime(new Date());
        assetLogService.insert(logDTO);
        return map;
    }

    /**
     * 创建日志对象
     *
     * @param assetId
     * @param serviceType
     * @return
     */
    public AssetLogDTO createAssetLog(String assetId, int serviceType) {
        String loginUserId = ThreadContextHelper.getUserId();
        String loginUserName = ThreadContextHelper.getUserName();
        //针对无人系统没有用户登陆时，默认是admin
        if (StringUtils.isBlank(loginUserId)) {
            loginUserId = "1";
            loginUserName = "系统管理员";
        }
        // 记录下载日志
        AssetLogDTO logDTO = new AssetLogDTO();
        logDTO.setId(ComUtil.getId());
        logDTO.setAssetId(assetId);
        logDTO.setServiceType(serviceType);
        logDTO.setStartTime(new Date());
        logDTO.setCallUserId(loginUserId);
        logDTO.setCallUserName(loginUserName);
        return logDTO;
    }

    /**
     * 模型查看
     *
     * @param assetId
     * @return
     * @throws Exception
     */
    public List<ColumnMeta> queryModel(String assetId) throws Exception {
        BdpAssetDTO asset = this.selectByPrimaryKey(assetId);
        CheckParaUtils.checkDbObjectValidity(asset, logger, String.format("没有查到数据，请确保id:%s的资产是否存在", assetId));

        List<ColumnMeta> list = new ArrayList<>();
        AssetLogDTO logDTO = createAssetLog(assetId, ApplyServiceType.MODEL.getCode());
        try {
            list = modelAdapter.getModelColumnList(assetId);
            logDTO.setCallStatus(1);
            logDTO.setCallResult("查询模型成功");
        } catch (Exception e) {
            logDTO.setCallStatus(0);
            logDTO.setCallResult(e.getMessage());
            logger.error("查询数据异常", e);
            throw e;
        }

        logDTO.setEndTime(new Date());
        assetLogService.insert(logDTO);
        return list;
    }

    /**
     * 文件下载
     */
    public void downloadFile(String assetId, String filePath, HttpServletRequest request, HttpServletResponse response) throws Exception {
        BdpAssetDTO asset = this.selectByPrimaryKey(assetId);
        CheckParaUtils.checkDbObjectValidity(asset, logger, String.format("没有查到数据，请确保id:%s的资产是否存在", assetId));
        AssetLogDTO logDTO = createAssetLog(assetId, ApplyServiceType.DOWNLOAD.getCode());
        try {
            fileAdapter.downloadFile(assetId, filePath, request, response);
            logDTO.setCallResult("下载文件【" + filePath + "】成功");
            logDTO.setCallStatus(1);
        } catch (Exception e) {
            logDTO.setCallStatus(0);
            logDTO.setCallResult(e.getMessage());
            logger.error("下载数据异常", e);
            throw e;
        }

        logDTO.setEndTime(new Date());
        assetLogService.insert(logDTO);
    }

    /**
     * 分页查询资产监控列表
     *
     * @throws Exception
     */
    public QueryRespBean<BdpAssetDTO> getAssetMonitorPageList(String catalogId, String keyWords, String assetType,
                                                              String releaseDept, String releaseDateBegin, String releaseDateEnd,
                                                              Integer pageNo, Integer pageSize) throws Exception {
        QueryRespBean<BdpAssetDTO> queryRespBean = new QueryRespBean<>();
        //文档密级
        String wordSecret = ThreadContextHelper.getWordSecret();
        PageHelper.startPage(pageNo, pageSize);
        Page<BdpAssetDTO> page = asssetPortalDao.getAssetMonitorPageList(catalogId, keyWords, assetType, releaseDept,
                releaseDateBegin, releaseDateEnd, wordSecret);
        valueConvert(page.getResult());
        queryRespBean.setResult(page);
        BdpLogUtil.log4Query(queryRespBean);
        return queryRespBean;
    }

    /**
     * API查看
     *
     * @param assetId
     * @return
     * @throws Exception
     */
    public Map<String, Object> queryApi(String assetId) throws Exception {
        BdpAssetDTO asset = this.selectByPrimaryKey(assetId);
        CheckParaUtils.checkDbObjectValidity(asset, logger, String.format("没有查到数据，请确保id:%s的资产是否存在", assetId));

        BdpAssetMountDataServiceDTO mountDataService = bdpAssetMountDataServiceService.queryByAssetId(assetId);
        CheckParaUtils.checkDbObjectValidity(mountDataService, logger, String.format("没有查到数据，请确保assetId:%s的数据服务是否存在", assetId));

        Map<String, Object> map = new HashMap<>(8);
        AssetLogDTO logDTO = createAssetLog(assetId, ApplyServiceType.API.getCode());
        try {
            map = getApiInfo(mountDataService);
            logDTO.setCallStatus(1);
            logDTO.setCallResult("查询API接口成功");
        } catch (Exception e) {
            logDTO.setCallStatus(0);
            logDTO.setCallResult(e.getMessage());
            logger.error("查询数据异常", e);
            throw e;
        }

        logDTO.setEndTime(new Date());
//        assetLogService.insert(logDTO);
        return map;
    }

    /**
     * 获取API信息
     *
     * @return API信息
     */
    private Map<String, Object> getApiInfo(BdpAssetMountDataServiceDTO mountDataService) {
        Map<String, Object> map = new HashMap<>(8);
        List<ApiParamDto> paramList = new ArrayList<>();

        // get请求带分页参数
        if (HttpMethod.GET.name().equalsIgnoreCase(mountDataService.getRequestMethod())) {
            ApiParamDto currentPage = new ApiParamDto();
            currentPage.setName("pageNo");
            currentPage.setCnName("当前页");
            currentPage.setRequired(1);
            currentPage.setExample("1");
            paramList.add(currentPage);
            ApiParamDto pageSize = new ApiParamDto();
            pageSize.setName("pageSize");
            pageSize.setCnName("每页大小");
            pageSize.setRequired(1);
            pageSize.setExample("10");
            paramList.add(pageSize);
        }

        List<JSONObject> columnInfoList = new ArrayList<>();
        List<ColumnDTO> columnInfoDtoList = JSONUtils.toList(mountDataService.getColumnInfo(), ColumnDTO.class);
        if (CollectionUtils.isNotEmpty(columnInfoDtoList)) {
            for (ColumnDTO columnInfo : columnInfoDtoList) {
                if (columnInfo.getIsParam()) {
                    ApiParamDto param = new ApiParamDto();
                    param.setName(columnInfo.getName());
                    param.setCnName(columnInfo.getCnName());
                    param.setRequired(0);
                    param.setExample("");
                    paramList.add(param);
                }
                if (columnInfo.getIsReturn()) {
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("columnName", columnInfo.getName());
                    jsonObject.put("description", columnInfo.getCnName());
                    jsonObject.put("type", columnInfo.getColumnType());
                    columnInfoList.add(jsonObject);
                }
            }
        }

        map.put("asset", mountDataService);
        map.put("paramList", paramList);
        map.put("token", "");
        dataResourceService.buildResponseData(mountDataService.getRequestMethod(), map, columnInfoList);
        return map;
    }

    /**
     * 报表查看
     *
     * @param assetId
     * @return
     * @throws Exception
     */
    public String queryReport(String assetId) throws Exception {
        BdpAssetDTO asset = this.selectByPrimaryKey(assetId);
        CheckParaUtils.checkDbObjectValidity(asset, logger, String.format("没有查到数据，请确保id:%s的资产是否存在", assetId));

        BdpAssetMountReportDTO mountReport = bdpAssetMountReportService.queryByAssetId(assetId);
        CheckParaUtils.checkDbObjectValidity(mountReport, logger, String.format("没有查到数据，请确保assetId:%s的报表是否存在", assetId));

        AssetLogDTO logDTO = createAssetLog(assetId, ApplyServiceType.REPORT.getCode());
        try {
            logDTO.setCallStatus(1);
            logDTO.setCallResult("查看报表成功");
        } catch (Exception e) {
            logDTO.setCallStatus(0);
            logDTO.setCallResult(e.getMessage());
            logger.error("查询数据异常", e);
            throw e;
        }

        logDTO.setEndTime(new Date());
        assetLogService.insert(logDTO);
        return null;
    }

    private void valueConvert(List<BdpAssetDTO> assetList) {
        //循环组装请求数据
        Map<String, Set<String>> convertFormData = new HashMap<>();
        for (BdpAssetDTO asset : assetList) {
            BusinessUtil.createConvertSet(convertFormData, Constants.BDP_DATA_SECRET_LEVEL_KEY, asset.getSecretLevel());
            BusinessUtil.createConvertSet(convertFormData, "BDP_DAM_RESOURCE_TYPE", asset.getAssetType());
            BusinessUtil.createConvertSet(convertFormData, SystemConstant.USER, asset.getReleaser());
            BusinessUtil.createConvertSet(convertFormData, SystemConstant.USER, asset.getCreatedBy());
            BusinessUtil.createConvertSet(convertFormData, SystemConstant.DEPT, asset.getReleaseDept());
        }
        if (convertFormData.size() > 0) {
            //获取请求结果
            Map<String, Map<String, String>> convertResultData = convertColumnClient.replace(convertFormData);
            Map<String, String> map = getAllSysOrgAndDept();

            //循环设置Alias或Name的值
            for (BdpAssetDTO asset : assetList) {
                asset.setSecretLevelName(BusinessUtil.convertFormat(convertResultData, Constants.BDP_DATA_SECRET_LEVEL_KEY, asset.getSecretLevel()));
                //资源类型
                asset.setAssetTypeName(BusinessUtil.convertFormat(convertResultData, "BDP_DAM_RESOURCE_TYPE", asset.getAssetType()));
                //发布人
                asset.setReleaserName(BusinessUtil.convertFormat(convertResultData, SystemConstant.USER, asset.getReleaser()));
                //创建人
                asset.setCreatedName(BusinessUtil.convertFormat(convertResultData, SystemConstant.USER, asset.getCreatedBy()));
                asset.setReleaseDeptName(BusinessUtil.convertFormat(convertResultData, SystemConstant.DEPT, asset.getReleaseDept()));
                asset.setReleaseScopeShowName(getOrgName(asset.getReleaseScope(), map));
                asset.setEffectiveTimeTypeStr(handelEffectiveTime(asset));
            }
        }
    }

    public Map<String, Object> queryTableDataNew(Map<String, Object> queryMap) {
        String assetId = MapUtils.getString(queryMap, "assetId");
        String paramJson = MapUtils.getString(queryMap, "paramJson");
        Integer pageNo = MapUtils.getInteger(queryMap, "pageNum");
        Integer pageSize = MapUtils.getInteger(queryMap, "pageSize");
        BdpAssetDTO asset = this.mapper.selectByAssetId(assetId);
        CheckParaUtils.checkDbObjectValidity(asset, logger, String.format("没有查到数据，请确保id:%s的资产是否存在", assetId));

        Map<String, Object> map = new HashMap<>(8);
        AssetLogDTO logDTO = createAssetLog(assetId, ApplyServiceType.DATA_QUERY.getCode());
        try {
            map = dataServiceAdapter.getDataListFromDBNew(assetId, pageNo, pageSize, paramJson);
            logDTO.setCallStatus(1);
            logDTO.setCallResult("查询数据成功");
        } catch (Exception e) {
            logDTO.setCallStatus(0);
            logDTO.setCallResult(e.getMessage());
            logger.error("查询数据异常", e);
            throw new BusinessException(e.getMessage(), e);
        }

        logDTO.setEndTime(new Date());
        assetLogService.insert(logDTO);
        //新增调用次数
        bdpAssetService.addCallCount(assetId);
        return map;
    }

    public Boolean queryApplyByAssetId(String assetId) {
        //申请按钮
        String loginUserId = ThreadContextHelper.getUserId();
        List<String> assetIdList = new ArrayList<>();
        assetIdList.add(assetId);
        List<AssetApplyDTO> assetApplyDTOList = assetApplyDao.getApplyListByIds(assetIdList, loginUserId);
        Map<String, String> assetApplyMap = handleAssetApply(assetApplyDTOList);
        BdpAssetDTO asset = bdpAssetService.selectByPrimaryKey(assetId);
        String apply = assetApplyMap.get(asset.getId());
        if (apply == null || serviceTypeCompare(asset.getOpenServiceType(), apply)) {
            return true;
        }
        return false;

    }

    private boolean serviceTypeCompare(String openServiceType, String apply) {
        List<String> openServiceTypeList = Arrays.asList(openServiceType.split(","));
        List<String> applyList = Arrays.asList(apply.split(","));
        applyList = applyList.stream().distinct().collect(Collectors.toList());//去重
        Collections.sort(applyList);//排序
        if (openServiceTypeList.size() == applyList.size()) {
            int i = 0;
            for (String s : openServiceTypeList) {
                if (!s.equals(applyList.get(i))) {
                    return true;
                }
                i++;
            }
        } else {
            return true;
        }
        return false;
    }
}